<?php

/**
 * HTML helper class.
 *
 * @version  $Id: html.php 2 2009-10-02 23:06:43Z perfilev $
 * @package  System
 */

class Html
{
	/**
	 * Convert special characters to HTML entities.
	 *
	 * @param   string   $value         String to convert.
	 * @param   boolean  $doubleEncide  Encode existing entities.
	 * @return  string
	 */
	public static function chars($value, $doubleEncode = true)
	{
		return htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8', $doubleEncode);
	}

	/**
	 * Create HTML link anchors. Note that the title is not escaped, to allow
	 * HTML elements within links (images, etc).
	 *
	 * @param   string  $uri         URL or URI string.
	 * @param   string  $title       Link text.
	 * @param   array   $attributes  HTML anchor attributes.
	 * @param   string  $protocol    Use a specific protocol.
	 * @return  string
	 */
	public static function anchor($uri, $title = null, array $attributes = array(), $protocol = null)
	{
		if (null === $title) {
			$title = $uri;
		}

		if ($uri === '') {
			$uri = Url::base($protocol);
		} elseif ($uri[0] !== '#' && strpos($uri, '://') === false) {
			$uri = Url::site($uri, $protocol);
		}

		$attributes['href'] = $uri;

		return '<a' . self::attributes($attributes) . '>' . $title . '</a>';
	}

	/**
	 * Compiles an array of HTML attributes into an attribute string.
	 *
	 * @param   array  $attributes  Attribute list.
	 * @return  string
	 */
	public static function attributes(array $attributes = null)
	{
		if (empty($attributes)) {
			return '';
		}
		$compiled = '';
		foreach ($attributes as $key => $value) {
			if ($value === null) {
				// Skip attributes that have NULL values
				continue;
			}
			$compiled .= ' ' . $key . '="' . htmlspecialchars($value, ENT_QUOTES, 'UTF-8') . '"';
		}
		return $compiled;
	}

	/**
	 * Compiles an array of breadcrumbs into an HTML string.
	 *
	 * @param   array   $crumbs     Associative array.
	 * @param   string  $separator  Separator to use.
	 * @return  string
	 */
	public static function breadcrumbs(array $crumbs, $separator = ' » ')
	{
		$compiled = '';
		$i = 0;
		foreach ($crumbs as $key => $value) {
			if ($i++ > 0) {
				$compiled .= $separator;
			}
			if ($key == '') {
				$compiled .= htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
			} else {
				$compiled .= self::anchor($key, htmlspecialchars($value, ENT_QUOTES, 'UTF-8'));
			}
		}
		return $compiled;
	}
}
